﻿using System.Net;
using System.Text;
using System.Text.RegularExpressions;

using EmbeddedSensorCloud.HTTP;
using SWE4.Data.EmbeddedSensorCloud.DTO.Request;
using Newtonsoft.Json;

namespace EmbeddedSensorCloud.Plugin.MicroERP
{
    public class CreateCustomerCommand : ICommand
    {
        #region Fields

        private ICustomerDAO _CustomerDao;
        private JsonSerializerSettings _JsonSettings;

        #endregion

        #region Constructor

        public CreateCustomerCommand(ICustomerDAO customerDao, JsonSerializerSettings jsonSettings)
        {
            this._CustomerDao = customerDao;
            this._JsonSettings = jsonSettings;
        }

        #endregion

        #region ICommand

        public bool CanExecute(Request param)
        {
            return (param.Method.ToUpperInvariant() == "POST" &&
                    Regex.IsMatch(param.Url, @"^/api/customer[/]?$", RegexOptions.IgnoreCase));
        }

        public ResponseEntity Execute(Request param)
        {
            if (string.IsNullOrWhiteSpace(param.Body))
            { throw new BadRequestException(); }

            var model = JsonConvert.DeserializeObject<CustomerRequestModel>(param.Body, this._JsonSettings);
            string returnString = this._CustomerDao.Create(model).ToString();

            return new ResponseEntity(Encoding.UTF8.GetBytes(returnString), HttpStatusCode.Created);
        }

        #endregion
    }
}
